<?php

namespace yan\tinymce;
use yii\helpers\Json;

/**
 * Main backend application asset bundle.
 */
class Tinymce extends \yii\base\Widget
{
    public $language = 'zh_TW';
    public $clientOptions = [];
    public function init()
    {
        parent::init();
        $this->language = str_replace('-', '_', \Yii::$app->language);
        $clientOptions = $this->clientOptions;
        $this->clientOptions = [
            // 不显示Powered by Tiny
            'branding' => false,
            'relative_urls' => false,
            'forced_root_block' => '',
            'valid_elements' => '*[*]',
            'height' => 500,
            'mobile' => [
                'theme' => 'mobile',
                'plugins' => 'undo redo bold italic underline link image bullist numlist fontsizeselect forecolor styleselect removeformat',
                'toolbar' => 'undo redo bold italic underline link image bullist numlist fontsizeselect forecolor styleselect removeformat',
            ],
            'plugins' => [
                'advlist autolink lists link image charmap print preview anchor',
                'searchreplace visualblocks code',
                'insertdatetime media table paste code imagetools responsivefilemanager',
            ],
            'toolbar' => 'undo redo |  formatselect | fontsizeselect bold italic forecolor backcolor  | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | image responsivefilemanager filemanager link unlink code',
            'file_picker_types' => ['image'],
            'external_filemanager_path' => '/filemanager/',
            'filemanager_access_key' => \Yii::$app->params['filemanager_access_keys'][0],
            'filemanager_title' => 'Filemanager',
            'external_plugins' => [
                'responsivefilemanager' => '/filemanager/responsivefilemanager/plugin.min.js',
                'filemanager' => '/filemanager/plugin.min.js'
            ],
            'content_css'=>[]
        ];
        if(!empty($clientOptions)){
            $this->clientOptions = array_merge($this->clientOptions, $clientOptions);
        }
    }
    public function run(){
        $this->registerClientScript();
    }
    protected function registerClientScript()
    {
        $js = [];
        $view = $this->getView();

        $assets = TinyMceAsset::register($view);

        // @codeCoverageIgnoreStart
        if ($this->language !== null && $this->language !== 'en') {
            $langFile = "tinymce/langs/{$this->language}.js";
            $assets->js[] = $langFile;
            $this->clientOptions['language_url'] = $assets->baseUrl . "/{$langFile}";
            $this->clientOptions['language'] = "{$this->language}";//Language fix. Without it EN language when add some plugins like codemirror 
        }
        // @codeCoverageIgnoreEnd

        $options = Json::encode($this->clientOptions);

        $js[] = "my_editor.init($options);";
        $view->registerJs(implode("\n", $js));
    }

}
